<?php

namespace app\tools;

/**
 * 自定义日志记录
 *
 * Class Logs
 * @package projects\tools
 */
class Logs
{

    /**
     * 信息记录
     *
     * @param string $title ''
     * @param array $data []
     * @param string $fileName ''
     * @param string $path ''
     * @return bool
     */
    public static function info(string $title = '', array $data = [], string $fileName = '', string $path = ''): bool
    {
        $dir = '/dataInfo';
        if (!$fileName || !$data) {
            return false;
        }
        $path = $dir . $path;
        self::write($title, $data, $fileName, $path);
        return true;
    }

    /**
     * 错误信息记录
     *
     * @param string $title ''
     * @param array $data []
     * @param string $fileName ''
     * @param string $path : 默认：error
     * @return false
     */
    public static function error(string $title = '', array $data = [], string $fileName = '', string $path = 'error'): bool
    {
        if (!$fileName || !$data) {
            return false;
        }
        self::write($title, $data, $fileName, $path, false);
        return true;
    }

    /**
     * 日志写入
     *
     * @param string $title 标题
     * @param array $data 数据信息
     * @param string $fileName 文件名
     * @param string $path 储存路径
     * @param bool $date 是否按日期路径存放
     */
    private static function write(string $title = '', array $data = [], string $fileName = '', string $path = '', bool $date = true): void
    {
        if ($date) {
            $path = public_path() . $path . '/' . date('Ymd');
            if (!is_dir($path)) {
                mkdir($path, 0770, true);
            }
        }
        $filePath = $path . '/' . $fileName . '.log';
        $file = fopen($filePath, "a");
        fwrite($file, date('Y-m-d H:i:s') . '---------' . $title . '：' . print_r($data, true));
        fclose($file);
    }
}